package oldtest;

import gui.*;

import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.Iterator;

import boardgame.Board;

import gui.GListener;

public class GButtonListener extends GListener {
	
	public GButtonListener(BoardGUI gui, Board board){
		super(gui, board);
	}
	
	protected String updateModel(ActionEvent e) {
		if (e.getSource().getClass() != GButton.class)
			return "Error: Not GButton Class";
		GButton temp = (GButton)e.getSource();		
		return updateModel(temp.getID()[0],temp.getID()[1]);
				
	}

	protected void updateGUI(ActionEvent e, String valid) {
		if (e.getSource().getClass() != GButton.class)
			return;
		if (valid.equals("")){			
			if (board.gameEnd()){			
				gui.update(e.getSource());
				gui.clear(board.getWinner());
			} else {
				gui.update(e.getSource());
				System.out.println(board.getCurrentPlayer());
			}
			if (((TicTacToeTest)board).aiStatus()&&!board.gameEnd()){
				int[] aiMove = ((TicTacToeTest)board).moveByAI().getPosition();
				System.out.println(aiMove[0]+","+aiMove[1]);
				updateModel(aiMove[0], aiMove[1]);
				if (board.gameEnd()){			
					gui.update(findButton(aiMove[0], aiMove[1]));					
					gui.clear(board.getWinner());
				} else {
					gui.update(findButton(aiMove[0], aiMove[1]));
					System.out.println(board.getCurrentPlayer());
				}
			}
		} else {
			gui.updateStatus(valid);
		}
	}
	
	private GButton findButton(int x, int y){
		Iterator<GButton> it = ((TicTacToeGUITest)gui).buttonGrid.iterator();
		while(it.hasNext()){
			GButton but = it.next();
			if (but.getID()[0]==x&&but.getID()[1]==y){
				gui.update(but);
				return but;
			}
		}
		return null;
	}
	
	private String updateModel(int x, int y){
		try {
			if (board.getCurrentPlayer() == 1)
				((TicTacToeTest)board).placePiece(new TicTac(x, y, 1));
			else
				((TicTacToeTest)board).placePiece(new TicTac(x, y, 2));
			return "";
		} catch (Exception ex){
			return ex.toString(); 
		}
	}
	
	protected String updateModel(ItemEvent e) {
		return null;
		// TODO Auto-generated method stub
		
	}
	
	protected void updateGUI(ItemEvent e, String valid) {
		// TODO Auto-generated method stub
		
	}

}
